package cn.ardy.common.util;

import java.security.SecureRandom;

public class SecureUtils {

    public static String genRandom(int length) {
        SecureRandom rand = new SecureRandom();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            sb.append(normalize(rand.nextInt(62)));
        }
        return sb.toString();
    }

    public static String genRandomNumbers(int length) {
        SecureRandom rand = new SecureRandom();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            sb.append(rand.nextInt(10));
        }
        return sb.toString();
    }

    private static String normalize(int randNumber) {
        StringBuilder result = new StringBuilder();
        do {
            int number = randNumber > 62 ? 0 : randNumber;
            if (number < 10) {
                result.append((char) (number + 48));
            } else if (number < 36) {
                result.append((char) (number + 65 - 10));
            } else if (number < 62) {
                result.append((char) (number + 97 - 36));
            }
            randNumber = randNumber - 62;
        } while (randNumber >= 0);

        return result.toString();
    }
}
